using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Win32;
using System.Windows.Forms;

namespace ArchSoft
{
    public class BatchBind
    {
        string _pageSetup;
        string _sourcePath;
        string _targetPath;
        string _description;
        public string _targetPathWithDateTime ="";


        readonly string TRANSMITTAL_SETUP = "TrangStandardTransmittalSetup";
        readonly string ETRANSMIT_SETUP_REGISTRYPATH = @"SOFTWARE\Autodesk\AutoCAD\R17.0\ACAD-5001:409\ETransmit\setups\TrangStandardTransmittalSetup";

        //source = C:\Documents and Settings\Trang 02\My Documents\newff\03 Output
        //Target = C:\Documents and Settings\Trang 02\My Documents\newff\04 Issued\DWG
        //FolList = 01 Client-02 Project Manager;

        public BatchBind(string source, string target)
        {
            _sourcePath = source;
            _targetPath = target;           
        }

        public BatchBind(string source, string target, string pagesetup, string des)
        {
            _sourcePath = source;
            _targetPath = target;
            _pageSetup = pagesetup;
            _description = des;
        }


        public BatchBind(string source, string target, string desc)
        {
            _sourcePath = source;
            _targetPath = target;
            _description = desc;
        }

        public bool DeleteTarget()
        {
            // Delete .bak file
            try
            {
                DirectoryInfo source = new DirectoryInfo(_sourcePath);
                foreach (DirectoryInfo subDir in source.GetDirectories())
                {
                    foreach (FileInfo file in subDir.GetFiles())
                    {
                        if (!file.Extension.Equals(".dwg") && !file.Extension.Equals(".dwt"))
                        {
                            file.Delete();
                        }
                    }
                }
                return true;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; }
        }

        private string GetUniqueName(string mainName)
        {
            int order = 0;
            string result = mainName;

            while (Directory.Exists(_targetPath + @"\" + result))
            {
                order++;
                result = mainName + "(" + order + ")";
            }
            return result;
        }

        private string GetCurrentDateTime()
        {
            DateTime dateTime = DateTime.Now;
            //return dateTime.Day+"-"+dateTime.Month+"-" + dateTime.Year+" " + dateTime.Hour+"-"+dateTime.Minute+"-"+dateTime.Second;
            return dateTime.Year + "." + dateTime.Month.ToString("00") + "." + dateTime.Day.ToString("00");
        }

        private string GetDateYYMMDD(DateTime date)
        {
            StringBuilder s = new StringBuilder();
            s.Append(date.Year.ToString().Substring(2));
            s.Append(date.Month.ToString("00"));
            s.Append(date.Day.ToString("00"));
            return s.ToString();
        }

        public void SetTransmittalSetupRegistry()
        {

            RegistryKey cadKey = Registry.CurrentUser.OpenSubKey(ETRANSMIT_SETUP_REGISTRYPATH);
            if (true)
            {
                cadKey = Registry.CurrentUser.CreateSubKey(ETRANSMIT_SETUP_REGISTRYPATH);
            }

            cadKey.SetValue("BindXref", 1, RegistryValueKind.DWord);
            cadKey.SetValue("Description", string.Empty, RegistryValueKind.String);
            cadKey.SetValue("DestFile", string.Empty, RegistryValueKind.String);
            cadKey.SetValue("DestFileAction", 0, RegistryValueKind.DWord);
            cadKey.SetValue("DestFolder", _targetPathWithDateTime, RegistryValueKind.String);
            cadKey.SetValue("FilePathOption", 0, RegistryValueKind.DWord);
            cadKey.SetValue("IncludeFont", 0, RegistryValueKind.DWord);
            cadKey.SetValue("IncludeMaterialTextures", 0, RegistryValueKind.DWord);
            cadKey.SetValue("", 0, RegistryValueKind.DWord);
            cadKey.SetValue("IncludeSSFiles", 1, RegistryValueKind.DWord);
            cadKey.SetValue("Name", TRANSMITTAL_SETUP, RegistryValueKind.String);
            cadKey.SetValue("PackageType", 1, RegistryValueKind.DWord);
            cadKey.SetValue("RootFolder", _sourcePath, RegistryValueKind.String);
            cadKey.SetValue("SaveDrawingFormat", 0, RegistryValueKind.DWord);
            cadKey.SetValue("SendMail", 0, RegistryValueKind.DWord);
            cadKey.SetValue("SetPlotterNone", 0, RegistryValueKind.DWord);
            cadKey.SetValue("UsePassword", 0, RegistryValueKind.DWord);
        }

        string batchFolder = AutocadHelper.Instance.BatchFiles;
        public void ProcessPDF(string childWindow)
        {
            _targetPathWithDateTime = GetCurrentDateTime();
            _targetPathWithDateTime = _targetPath + @"\" + GetUniqueName(_targetPathWithDateTime) + "_" + this._description;
            Directory.CreateDirectory(_targetPathWithDateTime);

            string newf = _sourcePath + "\\Xref\\" + "A_Template.dwt";

            string publicFolder = _sourcePath + Path.DirectorySeparatorChar + childWindow;



            string dir = "C:\\PDF";
            string dir1 = "C:\\PDF" + Path.DirectorySeparatorChar + childWindow;
            
            Directory.CreateDirectory(dir1);

            copyDirectory(publicFolder, dir1);

            string des = "C:\\PDF" + Path.DirectorySeparatorChar + "\\Xref";
            Directory.CreateDirectory(des);
            copyDirectory(_sourcePath + "\\Xref",des);

            RegistryKey myReg = Registry.CurrentUser.OpenSubKey("Software\\Adobe\\Acrobat Distiller\\7.0\\AdobePDFOutputFolder", true);
            myReg = Registry.CurrentUser.CreateSubKey("Software\\Adobe\\Acrobat Distiller\\7.0\\AdobePDFOutputFolder");
            myReg.SetValue("2", _targetPathWithDateTime, RegistryValueKind.String);

            RegistryKey myReg1 = Registry.CurrentUser.OpenSubKey("Software\\Adobe\\Acrobat Distiller\\7.0\\AdobePDFOutputFolder", true);
            myReg1.SetValue("", 0x00000002, RegistryValueKind.DWord);


            AutocadHelper.Instance.TemplateFileForPublishing = newf;
            AutocadHelper.Public(_pageSetup, dir, batchFolder);



            if (Directory.Exists(dir))
            {
                while (true)
                {
                    try
                    {
                        Directory.Delete(dir, true);
                        break;
                    }
                    catch
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                }
            }

            string Xrefpath = _sourcePath + "\\Xref";
            string[] fileName = Directory.GetFiles(Xrefpath);

            string[] filePDF = Directory.GetFiles(_targetPathWithDateTime);

            foreach (string file1 in fileName)
            {
                foreach (string file2 in filePDF)
                {
                    string fileName1 = Path.GetFileNameWithoutExtension(file1).ToString().Trim();
                    string fileName2 = Path.GetFileNameWithoutExtension(file2).ToString().Trim();
                    if (fileName2.IndexOf(fileName1) >= 0)
                    {
                        File.Delete(file2);
                    }
                }
            }

        }



        public void ProcessPDF()
        {
            _targetPathWithDateTime = GetCurrentDateTime();
            _targetPathWithDateTime = _targetPath + @"\" + GetUniqueName(_targetPathWithDateTime) + "_" + this._description;
            Directory.CreateDirectory(_targetPathWithDateTime);

            string newf = _sourcePath + "\\Xref\\" + "A_Template.dwt";

            string des = @"c:\MyDstDirectory";
            copyDirectory(_sourcePath, des);

            //string[] dir = Directory.GetDirectories(des, "XREF", SearchOption.AllDirectories);
            //foreach (string d in dir)
            //{
            //    DirectoryInfo di = new DirectoryInfo(d);
            //    di.Delete(true);
            //}

           // string publicFolder = _source;
            string publicFolder = des;

            

            RegistryKey myReg = Registry.CurrentUser.OpenSubKey("Software\\Adobe\\Acrobat Distiller\\7.0\\AdobePDFOutputFolder", true);
            myReg = Registry.CurrentUser.CreateSubKey("Software\\Adobe\\Acrobat Distiller\\7.0\\AdobePDFOutputFolder");
            myReg.SetValue("2", _targetPathWithDateTime, RegistryValueKind.String);

            RegistryKey myReg1 = Registry.CurrentUser.OpenSubKey("Software\\Adobe\\Acrobat Distiller\\7.0\\AdobePDFOutputFolder", true);
            myReg1.SetValue("", 0x00000002, RegistryValueKind.DWord);


            AutocadHelper.Instance.TemplateFileForPublishing = newf;
            AutocadHelper.Public(_pageSetup, publicFolder, batchFolder);

            Directory.Delete(des, true);

            string Xrefpath = _sourcePath + "\\Xref";
            string[] fileName = Directory.GetFiles(Xrefpath);

            string[] filePDF = Directory.GetFiles(_targetPathWithDateTime);

            foreach(string file1 in fileName)
            {
                foreach(string file2 in filePDF)
                {
                    string fileName1 = Path.GetFileNameWithoutExtension(file1).ToString().Trim();
                    string fileName2 = Path.GetFileNameWithoutExtension(file2).ToString().Trim();
                    if (fileName2.IndexOf(fileName1) >= 0)
                    {
                        File.Delete(file2);
                    }
                }
            }

        }

        public void ProcessPDFFiles(string templateFile)
        {
            //_targetPathWithDateTime = GetCurrentDateTime();
            //_targetPathWithDateTime = _targetPath + @"\" + GetUniqueName(_targetPathWithDateTime) + "_" + this._description;

            _targetPathWithDateTime = GetDateYYMMDD(DateTime.Now);
            _targetPathWithDateTime = _targetPath + @"\" + GetUniqueName(_targetPathWithDateTime) + "_PDF_" + this._description;
            Directory.CreateDirectory(_targetPathWithDateTime);

            string newf = templateFile + "\\Xref\\" + "A_Template.dwt";

            string publicFolder = _sourcePath;


            RegistryKey myReg = Registry.CurrentUser.OpenSubKey("Software\\Adobe\\Acrobat Distiller\\7.0\\AdobePDFOutputFolder", true);
            myReg = Registry.CurrentUser.CreateSubKey("Software\\Adobe\\Acrobat Distiller\\7.0\\AdobePDFOutputFolder");
            myReg.SetValue("2", _targetPathWithDateTime, RegistryValueKind.String);

            RegistryKey myReg1 = Registry.CurrentUser.OpenSubKey("Software\\Adobe\\Acrobat Distiller\\7.0\\AdobePDFOutputFolder", true);
            myReg1.SetValue("", 0x00000002, RegistryValueKind.DWord);


            AutocadHelper.Instance.TemplateFileForPublishing = newf;
            AutocadHelper.Public(_pageSetup, publicFolder, batchFolder);


            string Xrefpath = _sourcePath + "\\Xref";
            string[] fileName = Directory.GetFiles(Xrefpath);

            string[] filePDF = Directory.GetFiles(_targetPathWithDateTime);

            foreach (string file1 in fileName)
            {
                foreach (string file2 in filePDF)
                {
                    string fileName1 = Path.GetFileNameWithoutExtension(file1).ToString().Trim();
                    string fileName2 = Path.GetFileNameWithoutExtension(file2).ToString().Trim();
                    if (fileName2.IndexOf(fileName1) >= 0)
                    {
                        File.Delete(file2);
                    }
                }
            }



            if (Directory.Exists(publicFolder))
            {
                while (true)
                {
                    try
                    {
                        Directory.Delete(publicFolder, true);
                        break;
                    }
                    catch
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                }
            }



        }

        public  void copyDirectory(string Src, string Dst)
        {
            String[] Files;

            if (Dst[Dst.Length - 1] != Path.DirectorySeparatorChar)
                Dst += Path.DirectorySeparatorChar;
            if (!Directory.Exists(Dst)) Directory.CreateDirectory(Dst);
            Files = Directory.GetFileSystemEntries(Src);
            foreach (string Element in Files)
            {
                // Sub directories

                if (Directory.Exists(Element))
                    copyDirectory(Element, Dst + Path.GetFileName(Element));
                // Files in directory

                else
                    File.Copy(Element, Dst + Path.GetFileName(Element), true);
            }
        }



        private void DeleteTempFile()
        {
            DirectoryInfo issueWindow = new DirectoryInfo(_targetPathWithDateTime);
            foreach (FileInfo adrawing in issueWindow.GetFiles())
            {
                    adrawing.Delete();
            }

            foreach (DirectoryInfo dir in issueWindow.GetDirectories())
            {
                if (dir.Name.ToLower().Contains("xref"))
                {
                    dir.Delete(true);
                }
                else
                {
                    foreach (FileInfo adrawing in dir.GetFiles())
                    {
                        if (!adrawing.Extension.Contains("dwg") && !adrawing.Extension.Contains("dwt"))
                        {
                            adrawing.Delete();
                        }
                    }
                }
            }
        }

        public string GenerateScriptFile(string childWindow, List<string> drawings)
        {
            // Collect drawings
            List<string> issuedDrawings = new List<string>();
            DirectoryInfo issueWindow = new DirectoryInfo(_targetPathWithDateTime);
            foreach (DirectoryInfo dir in issueWindow.GetDirectories())
            {
                foreach (FileInfo adrawing in dir.GetFiles())
                {
                    issuedDrawings.Add(adrawing.FullName);
                }
            }

            // Generate script

            string tempFileName = _targetPathWithDateTime + @"\" + Guid.NewGuid().ToString() + ".scr";

            FileStream scriptFile = File.Open(tempFileName, FileMode.CreateNew);
            StreamWriter wr = new StreamWriter(scriptFile);

            wr.WriteLine("filedia 0");
            
             
            for (int i = 0; i < issuedDrawings.Count - 1; i++)
            {
                ScriptForADrawing(wr, false, issuedDrawings[i]);
            }
            ScriptForADrawing(wr, true,  issuedDrawings[issuedDrawings.Count - 1]);

            wr.WriteLine("filedia 1");
            wr.WriteLine("quit");
            wr.Flush();
            wr.Dispose();

            scriptFile.Close();
            scriptFile.Dispose();
            return tempFileName;          
        }       

        public string RunSciptFile(string filePath)
        {
            AutocadHelper helper = AutocadHelper.Instance;
            return helper.RunAutoCadScript(filePath, true);             
        }

        public void setDescription(string Descripton)
        {
            this._description = Descripton;
        }

        public string Process(string childWindow, List<string> drawings)
        {
            string str = "";           
            
           bool tpd = DeleteTarget(); if (!tpd) { return ""; }
            CopyOutputFolderToIssue(childWindow, drawings);
            string scriptFile = GenerateScriptFile(childWindow, drawings);
            str = RunSciptFile(scriptFile);
            DeleteTempFile();
            return str;
        }

        //private string _path;

        //public string getEmailPath
        //{
        //    set { _path = value;}
        //    get {return _path;}
        //}

        private void CopyOutputFolderToIssue(string window, List<string> selectedDrawings)
        {
            try
            {
                //_targetPathWithDateTime = GetCurrentDateTime();
                //_targetPathWithDateTime = _targetPath + @"\" + GetUniqueName(_targetPathWithDateTime) + "_" + this._description;
                _targetPathWithDateTime = GetDateYYMMDD(DateTime.Now);
                _targetPathWithDateTime = _targetPath + @"\" + GetUniqueName(_targetPathWithDateTime) + "_DWG_" + this._description;

                Directory.CreateDirectory(_targetPathWithDateTime);

                //   _path = _targetPathWithDateTime;

                DirectoryInfo sourceDir = new DirectoryInfo(_sourcePath);

                if (!window.Equals(string.Empty))
                {
                    string sourceWindow = _sourcePath + Path.DirectorySeparatorChar + window;
                    DirectoryInfo issuedwindow = Directory.CreateDirectory(_targetPathWithDateTime + @"\" + window);
                    if (selectedDrawings != null)
                    {
                        foreach (string drawingName in selectedDrawings)
                        {
                            File.Copy(sourceWindow + Path.DirectorySeparatorChar + drawingName, issuedwindow.FullName + Path.DirectorySeparatorChar + drawingName);
                        }
                    }
                    else
                    {
                        DirectoryInfo sourceWindowInfo = new DirectoryInfo(sourceWindow);
                        foreach (FileInfo drawing in sourceWindowInfo.GetFiles())
                        {
                            File.Copy(drawing.FullName, issuedwindow.FullName + Path.DirectorySeparatorChar + drawing.Name);
                        }
                    }

                }
                else
                {
                    foreach (DirectoryInfo dir in sourceDir.GetDirectories())
                    {
                        if (dir.Name != "Xref")
                        {
                            DirectoryInfo issuedwindow = Directory.CreateDirectory(_targetPathWithDateTime + @"\" + dir.Name);
                            foreach (FileInfo adrawing in dir.GetFiles())
                            {
                                File.Copy(adrawing.FullName, issuedwindow.FullName + @"\" + adrawing.Name);
                            }
                        }
                    }
                }
                //copy Xref vao!
                MoveDirectory(_sourcePath + "\\Xref", _targetPathWithDateTime + "\\Xref", false);
            }
            catch (Exception ex)
            {

            }
        }

        void MoveDirectory(string strSourceDir, string strDestDir, bool bDelSource)
        {
            if (Directory.Exists(strSourceDir))
            {
                try
                {
                    CopyDirectory(new DirectoryInfo(strSourceDir), new DirectoryInfo(strDestDir));
                }
                catch (Exception subEx)
                {
                    throw subEx;
                }
            }
        }

        void CopyDirectory(DirectoryInfo diSourceDir, DirectoryInfo diDestDir)
        {
            if (!diDestDir.Exists) diDestDir.Create();
            FileInfo[] fiSrcFiles = diSourceDir.GetFiles();
            foreach (FileInfo fiSrcFile in fiSrcFiles)
            {
                fiSrcFile.CopyTo(Path.Combine(diDestDir.FullName, fiSrcFile.Name));
            }
            //DirectoryInfo[] diSrcDirectories = diSourceDir.GetDirectories();
            //foreach (DirectoryInfo diSrcDirectory in diSrcDirectories)
            //{
            //    CopyDirectory(diSrcDirectory, new DirectoryInfo(Path.Combine(diDestDir.FullName, diSrcDirectory.Name)));
            //}
        }

        public string Process(string childWindow)
        {
            return Process(childWindow, null);
        }

        public string Process()
        {
            return Process(string.Empty, null);
        }

       
        public void ScriptForADrawing(StreamWriter wr,bool lastDrawing, string fileName)
        {
            wr.WriteLine("open \"" + fileName + "\"");
            wr.WriteLine("-XREF B * QSAVE");

            if (!lastDrawing)
            {
                wr.WriteLine("Close");
            }
        }
    }
}
